package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.service.*;
import cn.wolfcode.wolf2w.util.JsonResult;
import cn.wolfcode.wolf2w.util.UMEditorUploader;
import io.netty.util.internal.shaded.org.jctools.queues.MpscArrayQueue;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("travels")
public class TravelController {

    @Autowired
    private ITravelService travelService;

    @Autowired
    private IDestinationService destinationService;
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private ITravelCommentService travelCommentService;

    //分页
    @GetMapping("/query")
    public Object query(TravelQuery qo){
        return JsonResult.success(travelService.query(qo));
    }



    @GetMapping("/input")
    public Object input(String id){
        List<Destination> dests = destinationService.list();

        Map<String, Object> map = new HashMap<>();
        //编辑时回显
        if(StringUtils.hasLength(id)){
            Travel tv = travelService.get(id);
            map.put("tv", tv);
        }

        map.put("dests", dests);
        return JsonResult.success(map);

    }


    //上传图片
    @RequestMapping("/contentImage")
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }


    @RequireLogin  //必须登录之后才操作
    @PostMapping("/saveOrUpdate")
    public Object saveOrUpdate(Travel travel, HttpServletRequest request){
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        travel.setUserId(user.getId());
        travelService.saveOrUpdate(travel);
        //页面需要返回是新增/编辑游记
        return JsonResult.success(travel.getId());
    }


    @GetMapping("/detail")
    public Object detail(String id){
        return JsonResult.success(travelService.get(id));
    }


    /**
     *
     * 在接口中获取当前登录用户信息需要使用下面代码
     *
     * @GetMapping("xxx")
     * public Object xxx(HttpServletRequest request){
     *    String token = request.getHeader("token");
     *    UserInfo user = userInfoRedisService.getUserByToken(token);
     * }
     * 如果多个接口都需要获取, 这种操作方式就冗余 [代码重复很多遍了]
     *
     * 能不能使用某方式简化获取当前登录用户对象呢?
     *  方案: 原理springmvc中参数解析器
     *
     *  接口(请求映射方法)中所有参数注入靠的springmvc默认参数解析实现的
     *  现在想要注入当前登录用户对象,不能使用springmvc默认参数解析器
     *  需要自己额外定义一个:用户参数解析器, 专门来解析当前登录用户信息
     *
     *  >突破口: 怎么定义个springmvc参数解析器
     *
     */

    //简化的效果
    //在接口形式参数中声明用户对象, springmvc自动将当前登录用户对象注入进来
    @GetMapping("/getUser")
    public Object getUser(@UserParam UserInfo userInfo){
        //获取当前登录用户对象
        return JsonResult.success(userInfo);
    }

    //如果需要做用户编辑呢
    // 此时可以使用@UserParam 注解进行区分
    //参数中贴有这个注解表示需要使用自定义的参数解析器
    //参数中没贴有这个注解表示使用springmvc默认参数解析器
    @GetMapping("/updateUser")
    public Object updateUser(UserInfo userInfo){
        //获取当前登录用户对象
        return JsonResult.success(userInfo);
    }





    @RequireLogin
    @PostMapping("/commentAdd")
    public Object commentAdd(TravelComment comment,
                             @UserParam UserInfo userInfo){


        BeanUtils.copyProperties(userInfo, comment);
        comment.setUserId(userInfo.getId());
        travelCommentService.save(comment);


        return JsonResult.success();
    }




    @GetMapping("/comments")
    public Object comments(String travelId){
        return JsonResult.success(travelCommentService.queryByTravelId(travelId));
    }










}
